import os
import yaml
from utils.logger import Logger
from utils.config_loader import ConfigLoader

class BasePage:
    """所有页面对象的基类，不继承自 BaseCase"""
    
    # CONFIG_PATH = os.path.join(os.path.dirname(__file__), "../config/settings.yaml")
    # ENV = os.getenv("ENV", "staging")
    
    # test_case 是一个实例，用于调用测试用例中的方法
    def __init__(self, test_case):
        """初始化，接受 test_case 参数"""
        self.test_case = test_case  # 保存测试用例实例
        self.log = Logger.get_logger()
        # self.config = self._load_config()
        self.config = ConfigLoader.load()

    # def _load_config(self):
    #     """加载环境配置"""
    #     with open(self.CONFIG_PATH, encoding='utf-8') as f:
    #         config = yaml.safe_load(f)
    #         return config["environments"][self.ENV]
    
    def update_input(self, selector, text, clear_first=True, sensitive=False):
        """增强型输入方法"""
        # selector = self._normalize_locator(selector)
        if clear_first:
            self.test_case.clear(selector)
        if sensitive:
            self.log.info(f"输入敏感信息到 [{selector}] (内容已脱敏)")
        else:
            self.log.info(f"输入文本到 [{selector}]: {text}")
        self.test_case.type(selector, text)
        return self

    def load_elements(self, page_name: str):
        """加载页面元素配置文件"""
        element_path = os.path.join(
            os.path.dirname(__file__),
            "../config/elements",
            f"{page_name}.yaml"
        )
        with open(element_path, encoding="utf-8") as f:
            return yaml.safe_load(f)["elements"]

    def take_screenshot(self, name: str):
        """捕获屏幕截图"""
        path = f"logs/screenshots/{name}.png"
        self.test_case.save_screenshot(path)
        self.log.info(f"Screenshot saved: {path}")
        return self